package com.abc.fast.common.utils;

import com.abc.fast.common.constant.HttpStatus;
import com.abc.fast.common.domain.model.LoginUser;
import com.abc.fast.common.exception.BusinessException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * 安全工具类
 * @Author LiJunXi
 * @Date 2024-03-01 22:11
 */
public class SecurityUtil {

    /**
     * 判断密码是否相同
     * @param rawPassword 真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    /**
     * 密码加密
     * @param password
     * @return
     */
    public static String bCryptPassword(String password){
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 获取用户
     **/
    public static LoginUser getLoginUser() {
        try {
            Object principal = getAuthentication().getPrincipal();
            if (principal.equals("anonymousUser")){
                return null;
            }
            return (LoginUser) principal;
        }
        catch (Exception e) {
            throw new BusinessException(HttpStatus.UNAUTHORIZED, "获取用户信息异常");
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
}
